package sales

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// Market /**市场商品流向
func Market(r *gin.RouterGroup) {
	market := r.Group("/flow")
	{
		market.POST(sql.RequestAdd, marketAdd)
		market.POST(sql.RequestUpdate, marketUpdates)
		market.GET(sql.RequestList, marketList)
		market.GET(sql.RequestData, marketData)
		market.GET(sql.RequestDelete, marketDelete)
	}
}

func marketUpdates(c *gin.Context) {
	sql.HttpUpdates(c, &model.ProductFlow{}, nil)
}

func marketAdd(c *gin.Context) {
	sql.HttpAdd(c, &model.ProductFlow{}, nil)
}

func marketData(c *gin.Context) {
	sql.HttpData(c, &model.ProductFlow{}, func(db *gorm.DB) *gorm.DB {
		id := c.Query("id")
		db = db.
			Where("product_flow.id = ?", id).
			Select("product_flow.*," +
				"car_info.parking_space,car_info.plate_number,car_info.logistics_company,car_info.driver_phone").
			Joins("left join car_info on product_flow.car_id = car_info.id").
			Joins("left join product on product_flow.product_id = product.id")

		return db
	})
}

func marketDelete(c *gin.Context) {
	sql.HttpDeleteById(c, &model.ProductFlow{})
}

func marketList(c *gin.Context) {
	sql.HttpList(c, &[]model.ProductFlow{}, func(db *gorm.DB) *gorm.DB {
		var search = c.Query("search")
		db = db.
			Select("product_flow.*,car_info.plate_number,car_info.logistics_company,car_info.driver_phone").
			Joins("left join car_info on product_flow.car_id = car_info.id").
			Where(
				"product_flow.sales_area LIKE ? "+
					"OR CONCAT(product_flow.factory_no,product_flow.product_name) LIKE ? "+
					"OR car_info.plate_number LIKE ? "+
					"OR car_info.logistics_company LIKE ? "+
					"OR car_info.driver_phone LIKE ? "+
					"OR product_flow.customer LIKE ? ",
				"%"+search+"%", "%"+search+"%", "%"+search+"%", "%"+search+"%", "%"+search+"%", "%"+search+"%").
			Order("date DESC")
		return db
	})
}
